
    /**  
    * @Title: CreateServiceClass.java
    * @Package com.utils.table
    * @Description: 
    * @author likai
    * @date 2017年4月16日
    * @version V1.0  
    */
    
package com.frames.newtable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.utils.bean.BeanUtil;
import com.utils.date.DateUtil;
import com.utils.validate.Detect;


/**
    * @ClassName: CreateServiceClass
    * @Description: 创建项目的表的业务层，自动生成业务相关的controller、service、serviceParam,以及相关增删改查接口和实现mappper
    * @author likai
    * @date 2017年4月16日
    *
    */

public class CreateBusinessUtil{
	public static Logger log = LoggerFactory.getLogger(CreateBusinessUtil.class);
	
	private static  CreateBusinessUtil createBusinessUtil;
	private BusinessConfig businessConfig;

	public CreateBusinessUtil(BusinessConfig config) {
		super();
		this.businessConfig = config;
	}

	public static CreateBusinessUtil init(BusinessConfig config) {
		if (createBusinessUtil==null) {
			return new CreateBusinessUtil(config);
		}
		return createBusinessUtil;
	}
	
	
	public void create(String serviceName,String describe) throws Exception {
		
		String moduleSuffix= BeanUtil.columnToField2(businessConfig.moduleSuffix().toLowerCase());
		serviceName = BeanUtil.columnToField2(serviceName);
		
		if (Detect.notEmpty(businessConfig.controllerFilePath())&&Detect.notEmpty(businessConfig.controllerPackage())) {
			//创建controller
			String tmpClassName =businessConfig.controllerFilePath()+"/"+ serviceName + "Controller.java";
			File classFile = new File(tmpClassName);
			if (!classFile.exists()) {// 如果存在，则不重建
				createController(serviceName,businessConfig.controllerPackage(),businessConfig.servicePackage(),describe,classFile);
			}
		}
		if (Detect.notEmpty(businessConfig.serviceFilePath())&&Detect.notEmpty(businessConfig.servicePackage())) {
			//创建service接口
			String tmpClassName =businessConfig.serviceFilePath()+"/"+ serviceName + "Service.java";
			File classFile = new File(tmpClassName);
			if (!classFile.exists()) {// 如果存在，则不重建
				createService(serviceName, businessConfig.servicePackage(), describe, classFile);
			}
		}
		if (Detect.notEmpty(businessConfig.serviceImplFilePath())&&Detect.notEmpty(businessConfig.serviceImplPackage())) {
			//创建service接口实现类
			String tmpClassName =businessConfig.serviceImplFilePath()+"/"+ serviceName + "ServiceImpl.java";
			File classFile = new File(tmpClassName);
			if (!classFile.exists()) {// 如果存在，则不重建
				createServiceImpl(serviceName, businessConfig.serviceImplPackage(), businessConfig.servicePackage(), describe, classFile);
			}
			
		}
		
		if (Detect.notEmpty(businessConfig.moduleFilePath())&&Detect.notEmpty(businessConfig.modulePackage())) {
			//创建service业务数据库module接口
			if (businessConfig.userPrefixAsMapperDir()) {
				String path=businessConfig.moduleFilePath();
				path=path.substring(0, path.lastIndexOf("/"));
				if (!new File(path).exists()) {
					throw new Exception(path+"不存在！");
				}
				File dir=new File(businessConfig.moduleFilePath());
				if (!dir.exists()) {
					dir.mkdirs();
				}
			}
			String tmpClassName =businessConfig.moduleFilePath()+"/"+ serviceName+moduleSuffix + ".java";
			File classFile = new File(tmpClassName);
			if (!classFile.exists()) {// 如果存在，则不重建
				createMapper(serviceName, businessConfig.modulePackage(),moduleSuffix, describe, classFile);
			}
			
		}
		if (Detect.notEmpty(businessConfig.mapperFilePath())) {
			//创建module的mapper.xml
			if (businessConfig.userPrefixAsMapperDir()) {
				String path=businessConfig.mapperFilePath();
				path=path.substring(0, path.lastIndexOf("/"));
				if (!new File(path).exists()) {
					throw new Exception(path+"不存在！");
				}
				File dir=new File(businessConfig.mapperFilePath());
				if (!dir.exists()) {
					dir.mkdirs();
				}
			}
			String tmpClassName =businessConfig.mapperFilePath()+"/"+ serviceName+moduleSuffix + "Mapper.xml";
			File classFile = new File(tmpClassName);
			if (!classFile.exists()) {// 如果存在，则不重建
				createMapperXml(businessConfig.modulePackage()+"."+serviceName+moduleSuffix,classFile);
			}
			
		}
		log.info("------创建成功-----");
	}
	
	private void createController(String className,String classPackage,String servicePackage,String describe,File classFile) {
		try {
			classFile.createNewFile();
			StringBuilder sb = new StringBuilder();
			sb.append("package " + classPackage + ";\n\n");
			
			sb.append("import org.springframework.web.bind.annotation.RestController;\n");
			sb.append("import javax.annotation.Resource;\n");
			sb.append("import io.swagger.annotations.Api;\n");
			sb.append("import org.springframework.web.bind.annotation.RequestMapping;\n");
			sb.append("import "+businessConfig.superPackage()+".SuperApi;\n");
			sb.append("import org.slf4j.Logger;\n");
			sb.append("import org.slf4j.LoggerFactory;\n");
			sb.append("import "+servicePackage+"."+className+"Service;\n");
			sb.append("\n\n");
			sb.append("/**\n	* @ClassName: "+className+"Controller\n	* @Description: "+describe+"\n	* @author likai\n	* @date "+DateUtil.CHINESE.getDateText(new Date())+"\n	*\n	*/\n\n");
			sb.append("@RestController\n");
			sb.append("@RequestMapping(\"/"+BeanUtil.lowerCaseFirst(className)+"\")\n");
			sb.append("@Api(description = \""+describe+"\")\n");
			sb.append("@SuppressWarnings({\"rawtypes\",\"unchecked\"})\n");
			sb.append("public class " + className + "Controller extends SuperApi{\n\n");
			//
			sb.append("	public static Logger log = LoggerFactory.getLogger("+className+"Controller.class);\n");
			sb.append("	@Resource\n");
			sb.append("	public "+className+"Service "+BeanUtil.lowerCaseFirst(className)+"ServiceImpl;\n");
			sb.append("\n\n}\n\n");
			OutputStream os = new FileOutputStream(classFile);
			PrintStream ps = new PrintStream(os);
			ps.print(sb);

			os.flush();
			os.close();
			ps.flush();
			ps.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private void createService(String className,String classPackage,String describe,File classFile) {
		try {
			classFile.createNewFile();
			StringBuilder sb = new StringBuilder();
			sb.append("package " + classPackage + ";\n\n");
			
			sb.append("/**\n	* @ClassName: "+className+"Service\n	* @Description: "+describe+"\n	* @author likai\n	* @date "+DateUtil.CHINESE.getDateText(new Date())+"\n	*\n	*/\n\n");
			sb.append("@SuppressWarnings(\"rawtypes\")\n");
			sb.append("public interface " + className + "Service{\n\n");
			sb.append("\n}\n\n");
			OutputStream os = new FileOutputStream(classFile);
			PrintStream ps = new PrintStream(os);
			ps.print(sb);

			os.flush();
			os.close();
			ps.flush();
			ps.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private void createServiceImpl(String className,String classPackage,String servicePackage,String describe,File classFile) {
		try {
			classFile.createNewFile();
		//	String mapperSuffix= BeanUtil.columnToField2(getProperty("mapperSuffix").toLowerCase());
			StringBuilder sb = new StringBuilder();
			sb.append("package " + classPackage + ";\n\n");
			sb.append("import org.slf4j.Logger;\n");
			sb.append("import org.slf4j.LoggerFactory;\n");
			sb.append("import "+businessConfig.superPackage()+".SuperService;\n");
			sb.append("import org.springframework.stereotype.Service;\n");
			sb.append("import org.springframework.transaction.annotation.Transactional;\n");
			//sb.append("import javax.annotation.Resource;\n");
			sb.append("import "+servicePackage+"."+className+"Service;\n");
/*			sb.append("import "+serviceParamPackage+".TableParamDeal;\n");
			sb.append("import "+serviceParamPackage+".BussinessParamDeal;\n");*/
			sb.append("\n\n");
			sb.append("/**\n	* @ClassName: "+className+"ServiceImpl\n	* @Description: "+describe+"\n	* @author likai\n	* @date "+DateUtil.CHINESE.getDateText(new Date())+"\n	*\n	*/\n\n");
			sb.append("@Service\n");
			sb.append("@Transactional\n");
			sb.append("@SuppressWarnings({\"rawtypes\",\"unchecked\"})\n");
			sb.append("public class " + className + "ServiceImpl extends SuperService implements "+className+"Service{\n\n");
			sb.append("	public static Logger log = LoggerFactory.getLogger("+className+"ServiceImpl.class);\n");
			//
/*			sb.append("	@Resource\n");
			sb.append("	public TableParamDeal tableParamDeal;\n");
			sb.append("	@Resource\n");
			sb.append("	public BussinessParamDeal bussinessParamDeal;\n");*/
			sb.append("\n\n}\n\n");
			OutputStream os = new FileOutputStream(classFile);
			PrintStream ps = new PrintStream(os);
			ps.print(sb);

			os.flush();
			os.close();
			ps.flush();
			ps.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void createMapper(String className,String classPackage,String mapperSuffix,String describe,File classFile) {
		try {
			classFile.createNewFile();
			StringBuilder sb = new StringBuilder();
			sb.append("package " + classPackage + ";\n\n");
			
			sb.append("/**\n	* @ClassName: "+className+mapperSuffix+"\n	* @Description: "+describe+"\n	* @author likai\n	* @date "+DateUtil.CHINESE.getDateText(new Date())+"\n	*\n	*/\n\n");
			sb.append("public interface " + className+mapperSuffix + "{\n\n");
			sb.append("\n}\n\n");
			OutputStream os = new FileOutputStream(classFile);
			PrintStream ps = new PrintStream(os);
			ps.print(sb);

			os.flush();
			os.close();
			ps.flush();
			ps.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	private  void createMapperXml(String mapperServicClass,File classFile) {
		try {
			classFile.createNewFile();
			StringBuilder sb = new StringBuilder();
			sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
			sb.append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n");
			sb.append("<mapper namespace=\""+mapperServicClass+"\" >\n\n\n\n");									
			sb.append("</mapper>");
			OutputStream os = new FileOutputStream(classFile);
			PrintStream ps = new PrintStream(os);
			ps.print(sb);
			os.flush();
			os.close();
			ps.flush();
			ps.close();
		}catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	
}
